package controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import domain.Person;
import services.PersonService;

@Controller
@RequestMapping("/main")
public class MainController {
	protected static Logger logger = Logger.getLogger(MainController.class);
	@Resource(name = "persionService")
	PersonService personService;

	@RequestMapping(value = "/persons", method = RequestMethod.GET)
	public String getPersons(Model model) {
		logger.info("Retrived all persons");
		List<Person> persons = personService.getAll();
		model.addAttribute("listPerson", persons);
		return "personPage";
	}

	@RequestMapping(value = "/persons/add", method = RequestMethod.GET)
	public String addPerson(Model model) {
		logger.info("Received request to show add page");
		model.addAttribute("newPerson", new Person());
		return "addPage";
	}

	@RequestMapping(value = "/persons/add", method = RequestMethod.POST)
	public String add(@ModelAttribute("newPerson") Person person) {
		logger.info("Received request to add new person");
		personService.addPerson(person);
		return "addedPage";
	}

	@RequestMapping(value = "/persons/delete", method = RequestMethod.GET)
	public String delete(
			@RequestParam(value = "id", required = true) Integer id, Model model) {
		logger.info("Received request to delete a person");
		personService.deletePerson(id);
		model.addAttribute("id", id);
		return "deletedPage";
	}

	@RequestMapping(value = "/persons/edit", method = RequestMethod.GET)
	public String editPerson(
			@RequestParam(value = "id", required = true) Integer id, Model model) {
		logger.info("Received request to show edit page");
		Person person = personService.getPersonById(id);
		model.addAttribute("existPerson", person);
		return "editPage";
	}

	@RequestMapping(value = "/persons/edit", method = RequestMethod.POST)
	public String edit(@ModelAttribute(value = "existPerson") Person person,
			Integer id, Model model) {
		logger.info("Received request to update person");
		person.setId(id);
		personService.editPerson(person);
		model.addAttribute("id", id);
		return "edittedPage";
	}
}
